package com.doradance.app.home;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.doradance.R;
import com.doradance.account.ParamKey;
import com.doradance.account.UrlCenter;
import com.doradance.common.http.MyHttpRequest;
import com.doradance.entity.AllCommentsEntity;
import com.doradance.entity.CoursesIdEntity;
import com.doradance.entity.UpdataDetailEntity;
import com.example.xlhratingbar_lib.XLHRatingBar;
import com.pachong.android.baseuicomponent.activity.BaseActivity;
import com.pachong.android.framework.httprequest.UrlParams;
import com.pachong.android.framework.httprequest.responsecallbacks.DataRequestListener;
import com.pachong.android.frameworkbase.utils.EasyToast;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

public class UpCommentsActivity extends BaseActivity {
    String course_id;
    @Bind(R.id.ratingbarId_comments)
    XLHRatingBar mRatingbarIdComments;
    @Bind(R.id.et_comment_content)
    EditText mEtCommentContent;
    @Bind(R.id.tv_comment_count)
    TextView mTvCommentCount;
    @Bind(R.id.tv_evaluate_finish)
    TextView mTvEvaluateFinish;
    private int num = -1;
    private int num1 = 50;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        course_id = getIntent().getStringExtra("course_id");
        hideToolbar();
        initToolsBar();
    }

    private void initToolsBar() {
//        setTitle(R.string.write_evaluate);
//        getCustomToolbar().addLeftImageButton(R.mipmap.back, new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                finish();
//            }
//        });
//        getCustomToolbar().addRightButton(R.string.complete, new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                upData();
//
//            }
//        });
        mRatingbarIdComments.setOnRatingChangeListener(new XLHRatingBar.OnRatingChangeListener() {
            @Override
            public void onChange(int i) {
                num = i;
            }
        });

        mEtCommentContent.addTextChangedListener(new TextWatcher() {
            private CharSequence wordNum;//记录输入的字数.
            private int selectionStart;
            private int selectionEnd;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                wordNum = s;//实时记录输入的字数
            }

            @Override
            public void afterTextChanged(Editable s) {
                int number = num1 - s.length();
                //TextView显示剩余字数
                mTvCommentCount.setText(s.length() + "/50");
                selectionStart = mEtCommentContent.getSelectionStart();
                selectionEnd = mEtCommentContent.getSelectionEnd();
                if (wordNum.length() > num1) {
                    //删除多余输入的字（不会显示出来）
                    s.delete(selectionStart - 1, selectionEnd);
                    int tempSelection = selectionEnd;
                    mEtCommentContent.setText(s);
                    mEtCommentContent.setSelection(tempSelection);//设置光标在最后
                }
            }
        });
    }

    private void upData() {

        if (num == -1) {
            EasyToast.showToast(getApplicationContext(), "请选择评分");
        } else {
            MyHttpRequest request = new MyHttpRequest(this);
            JSONObject joj = new JSONObject();
            try {
                joj.put("course_id", course_id);
                joj.put("grade", num);
                joj.put("content", mEtCommentContent.getText().toString().trim());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            request.post(UrlCenter.COURSE_COMMENTS, joj, new DataRequestListener<String>(String.class
            ) {
                @Override
                public void onStart(Context context, String url) {
                    super.onStart(context, url);
                    mTvEvaluateFinish.setClickable(false);
                }

                @Override
                public void onSuccess(String o) {
                    super.onSuccess(o);
                    initEvaluate();

                }

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    super.onFailure(t, errorNo, strMsg);
                    EasyToast.showToast(getApplicationContext(), strMsg);
                    mTvEvaluateFinish.setClickable(true);
                }
            });

        }
    }

    private void initEvaluate() {
        MyHttpRequest request = new MyHttpRequest(this);
        String coursesUrl = String.format(UrlCenter.COURSES_ID, course_id);
        request.get(coursesUrl, null, new DataRequestListener<CoursesIdEntity>(CoursesIdEntity.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(CoursesIdEntity o) {
                super.onSuccess(o);
                mTvEvaluateFinish.setClickable(true);
                updataList(o);
                finish();
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                mTvEvaluateFinish.setClickable(true);
                EasyToast.showToast(getApplicationContext(), strMsg);
            }
        });
    }

    private void updataList(final CoursesIdEntity o1) {
        MyHttpRequest request = new MyHttpRequest(UpCommentsActivity.this);
        UrlParams urlParams = new UrlParams();
        Log.e("datadatadata", 0 + "");
        urlParams.put("course_id", course_id);
        urlParams.put("last_id", 0 + "");
        urlParams.put(ParamKey.SIZE, 10 + "");
        request.get(UrlCenter.ALL_COMMENTS, urlParams, new DataRequestListener<List<AllCommentsEntity>>(AllCommentsEntity.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(List<AllCommentsEntity> o) {
                super.onSuccess(o);
                EasyToast.showToast(getApplicationContext(), "评论成功");
                EventBus.getDefault().post(new UpdataDetailEntity(o1, o));
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_up_comments, null);
    }

    public static void start(Activity activity, String course_id) {
        Intent intent = new Intent(activity, UpCommentsActivity.class);
        intent.putExtra("course_id", course_id);
        activity.startActivity(intent);
    }

    @OnClick({R.id.iv_comments_back, R.id.tv_evaluate_finish})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_comments_back:
                finish();
                break;
            case R.id.tv_evaluate_finish:
                upData();
                break;
        }
    }
}
